<!-- 编辑弹窗 -->
<template>
  <div class="ele-body">
  <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
    <el-card  >  
      <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
        <div style="width: 50%;" >基础信息</div>
        <div style="width: 50%;display: flex;justify-content:end;" >
          <div v-show="form.status>=0" style="width: 30%;color:var(--color-primary)" >付款单号:{{ form.paymentNo }}</div>
        </div>
      </div>      
      <el-row :gutter="24">
        <el-col :md="6" :sm="24">
          <el-form-item label="供应商:" prop="supplierId">
            <el-select  v-model="form.supplierId" filterable clearable placeholder="请选择供应商" style="width:100%" @change="changeSupplier">
              <el-option  v-for="item in supplierDatas" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
          </el-form-item>
        </el-col>
        <el-col :md="6" :sm="24">
          <el-form-item label="付款账户:" prop="bankAccountId">
            <el-select  v-model="form.bankAccountId" filterable clearable placeholder="请选择付款账户" style="width:100%"  @change="changeBackAccount" >
              <el-option  v-for="item in bankAccountDatas" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
          </el-form-item>
        </el-col>
        <el-col :md="6" :sm="24">
          <el-form-item label="币种:" prop="currencyId">
            <el-select  v-model="form.currencyId" filterable clearable disabled placeholder="请选择币种" style="width:100%" @change="changeCurrency">
              <el-option  v-for="item in currencyFilterDatas" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :md="6" :sm="24">
          <el-form-item label="汇率:" prop="rate">
            <el-input v-model="form.rate" placeholder="请输入汇率" disabled  >
            </el-input>
          </el-form-item>
        </el-col> -->
        <!-- <el-col :md="6" :sm="24">
            <el-form-item label="应付金额:" prop="payAmount">
              <el-input v-model="form.payAmount" placeholder="请输入应付金额"  disabled >
              </el-input>
            </el-form-item>
        </el-col>
        <el-col :md="6" :sm="24">
          <el-form-item label="核销金额:" prop="auitAmount">
            <el-input v-model="form.auitAmount" placeholder="请输入核销金额"   disabled>
            </el-input>
          </el-form-item>
        </el-col>
       
        <el-col :md="6" :sm="24">
            <el-form-item label="应收金额" prop="payAmountCn">
              <el-input v-model="form.payAmountCn" placeholder="请输入应付金额"   prefix-icon="el-icon-_rmb" disabled >
              </el-input>
            </el-form-item>
        </el-col>
        <el-col :md="6" :sm="24">
          <el-form-item label="核销金额" prop="auitAmountCn">
            <el-input v-model="form.auitAmountCn" placeholder="请输入核销金额"  prefix-icon="el-icon-_rmb"  disabled >
            </el-input>
          </el-form-item>
        </el-col> -->
        <el-col :md="24" :sm="24" >
          <el-form-item label="备注:"  >
            <el-input :rows="2"
                clearable
                type="textarea"
                :maxlength="200"
                v-model="form.remark"
                placeholder="请输入备注说明" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>
    <el-card  style="margin-top: 10px">
      <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
        <div style="width: 8%;" >付款明细</div>
        <div style="width: 92%;display: flex;justify-content:start;" >
          <div style="width: 100%;color:var(--color-primary)" > 
              <el-button type="primary" class="ele-btn-icon" icon="el-icon-plus"  style="width: 10%;" @click="OpenProductList"  >应付核销账 </el-button>
            </div>
        </div>
      </div> 
      <el-table :data="form.items" ref="items"  :border="true" style="width: 100%" :height="tableHeight" :full-height="tableFullHeight" show-summary :summary-method="getSummaries"  :cell-style="cellStyle">
        <el-table-column type="index" width="50" align="center" label="序号" />
        <el-table-column label="单据编号"   align="center">
          <template slot-scope="{ row }">
            <el-form-item label-width="10" style="margin-bottom:0;" >
              <!-- <span>{{ row.orderNo }}</span> -->
              <el-link  type="primary"   @click="clickbillNo(row)" >{{ row.orderNo }}</el-link>
            </el-form-item>
          </template>
        </el-table-column>
        <!-- <el-table-column label="单据名称"   align="center">
          <template slot-scope="{ row }">
            <el-form-item label-width="10" style="margin-bottom:0;" >
              <el-link  type="primary"   @click="clickbillNo(row)" >{{ row.orderNo }}</el-link>
            </el-form-item>
          </template>
        </el-table-column> -->
        <el-table-column label="应付金额"   align="center">
            <template slot-scope="{ row }">
              <el-form-item label-width="10" style="margin-bottom:0;" >
                <span>{{ row.payAmount }}</span>
              </el-form-item>
            </template>
        </el-table-column>
        <!-- <el-table-column label="核销金额" align="center"  >
          <template slot-scope="{ row }">
            <span>{{ row.auitAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="汇率" align="center" >
            <template slot-scope="{ row }">
              <span>{{ row.rate }}</span>
            </template>
        </el-table-column> -->
        <el-table-column label="核销金额" align="center"  >
          <template slot-scope="{row,$index}">
            <el-form-item label-width="10" style="margin-bottom:0;" :prop="'items.'+ $index+'.auitAmount'" :rules="itemRules.auitAmount" >
              <el-input  v-model="row.auitAmount"  placeholder="请输入核销金额" @change="setAmount(row,$index)"  @keyup.native="row.auitAmount = row.auitAmount.replace(/[^\d.]/g,'');
                row.auitAmount = row.auitAmount.replace(/\.{2,}/g,'.');
                row.auitAmount = row.auitAmount.replace(/^\./g,'');
                row.auitAmount = row.auitAmount.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                row.auitAmount = row.auitAmount.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="汇率" align="center"  width="100">
          <template slot-scope="{row,$index}">
            <el-form-item label-width="10" style="margin-bottom:0;" :prop="'items.'+ $index+'.rate'" :rules="itemRules.rate" >
              <el-input  v-model="row.rate"  placeholder="请输入汇率" @change="setAmount(row,$index)"  @keyup.native="row.rate = row.rate.replace(/[^\d.]/g,'');
                row.rate = row.rate.replace(/\.{2,}/g,'.');
                row.rate = row.rate.replace(/^\./g,'');
                row.rate = row.rate.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                row.rate = row.rate.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="币种" align="center" width="120">
          <template slot-scope="{ row ,$index }">
            <el-form-item label-width="10" style="margin-bottom:0;"  :prop="'items.'+ $index+'.currencyId'" >
              <el-select  disabled  filterable v-model="row.currencyId" placeholder="请选择收货仓库" class="ele-fluid" >
                <el-option v-for="item in currencyDatas" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="应付金额(￥)" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.payAmountCn }}</span>
          </template>
        </el-table-column>
        <el-table-column label="核销金额(￥)" align="center" >
          <template slot-scope="{ row }">
            <span>{{ row.auitAmountCn }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center"  width="80" :resizable="false" v-if="this.isUpdate!=3">
          <template slot-scope="{ row , $index}">
            <span class="ele-action">
              <el-link  icon="el-icon-delete" type="danger" :underline="false" @click="remove(row, $index)" >删除</el-link>
            </span>
          </template>
        </el-table-column>

        <!-- <el-table-column label="订单类型" align="center" width="150">
          <template slot-scope="{ row ,$index }">
            <el-form-item label-width="10" style="margin-bottom:0;"  :prop="'items.'+ $index+'.orderType'">
              <el-select disabled filterable v-model="row.orderType" placeholder="请选择收货仓库" class="ele-fluid" >
                <el-option v-for="item in orderTypeDatas" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column> -->
      </el-table>
    </el-card>
    <el-card shadow="never"> </el-card>
  </el-form>
  <div>
    <div class="ele-dailog-bottom" >
      <div class="left"  style="display: flex;width: 50%;">
      </div>
      <div class="right" style="display: flex;width: 32%;">
        <el-button type="primary" v-show="this.isUpdate!=3 &&  form.status!=5" @click="save" :loading="loading" v-permission="'Financial_Payment_Save'" >
          挂单
        </el-button>
        <el-button type="warning" v-show="this.isUpdate!=3 &&  form.status!=5" @click="settle" :loading="loadingAudit" v-permission="'Financial_Payment_Audit'" >
          过账
        </el-button>
        <el-button type="danger" v-show="form.status==5"  @click="unAudit"   :loading="loadingUnAudit" v-permission="'Financial_Payment_UnAudit'" >
          反过账
        </el-button>
        <el-button @click="handleClose">关闭</el-button>
      
      </div>
    </div>
  </div>
  <!-- <div slot="footer">
    <el-button type="primary" v-show="this.btnIndex!=3 &&  form.status!=5"  :loading="loading" @click="save" >
      挂单
    </el-button>
    <el-button type="warning" v-show="this.btnIndex!=3 &&  form.status!=5" :loading="loading" @click="settle" >
      过账
    </el-button>
    <el-button type="danger" v-show="form.status==5"  @click="unAudit"   >
      反过账
    </el-button>
    <el-button @click="handleClose">关闭</el-button>
  </div> -->
 <!-- 编辑弹窗 -->
 <paymentauitList :data="current" :visible.sync="showrecreceiptList" @callback="reloadauitList"  />
</div>
</template>
<script>

 import paymentauitList from '../components/paymentauit-list.vue';
 import { QueryAllChildDictViewByCode } from '@/api/systemmanager/dictmanager';
 import { GetAllBSupplier} from '@/api/basicdatamanager/supplier';
 import { GetAllBackAccount} from '@/api/basicdatamanager/bankaccount';
 import { QueryModelByScurrencyId} from '@/api/basicdatamanager/ratemanager';
 import { AddPayment, UpdatePayment,AuitPayment,QueryPaymentById,AntiPayment } from '@/api/finance/payment';
 import { removePageTab, reloadPageTab,setPageTabTitle } from '@/utils/page-tab-util';


  export default {
    name: 'PaymentEdit',
    props: {
      // 弹窗是否打开
      visible: Boolean,
      // 修改回显的数据
      data: Object,
      // 按钮索引
      btnIndex:String,
    },
    components: {paymentauitList},
    data() {
      return {
        // 表单数据
        form: {rate:0,currencyId:'',items:[]},
        fixedHeight:true,
        // 表单验证规则
        rules: {
          customerId: [{required: true,message: '请选择供应商',trigger: 'blur'}],
          bankAccountId: [{required: true,message: '请选择账户',trigger: 'blur'}],
          supplierId: [{required: true,message: '请选择供应商',trigger: 'blur'}],
          // auitAmount: [{required: true,message: '请输入合同号',trigger: 'blur'}],
          currencyId: [{required: true,message: '请选择币种',trigger: 'blur'}],
        },
        itemRules: {
          auitAmount: [{required: true,message: '请输入核销金额',trigger: 'blur'}],
          rate: [{required: true,message: '请输入汇率',trigger: 'blur'}],
        },
        RMBId:'',
        current:null,
        // 提交状态
        loading: false,
        loadingAudit: false,
        loadingUnAudit: false,
        // 是否是修改
        isUpdate: 1,
        paymentId:'',
        currencyDatas:[],
        // 当前币种加人民币
        currencyFilterDatas:[],
        supplierDatas:[],
        bankAccountDatas:[],
        showrecreceiptList:false,
        computeDirection:2,//默认奈拉
        
      };
    },
    computed: {
      // 表格高度
      tableHeight() {
        var fh = this.fixedHeight ? 'calc(100vh - 450px)' : void 0;

        return fh;
      },
      // 表格全屏时高度
      tableFullHeight() {
        var fh =  this.fixedHeight ? 'calc(100vh - 380px)' : null;

        return fh;
      },
    },
    
    //初始化数据
    mounted(){

      if(this.isUpdate == 2 || this.isUpdate == 3){
        this.setData(this.paymentId);
      }else if(this.isUpdate == 1){
        this.$refs['form'].clearValidate();
        this.form={rate:0,currencyId:'',payAmount:0,payAmountCn:0,auitAmount:0,auitAmountCn:0,items:[]};
        this.isUpdate = 1;
      }
    },
    created(){
      this.initData();
      this.isUpdate = this.$route.query.isUpdate;
      this.paymentId = this.$route.query.paymentId;
      if(this.isUpdate == 1)  setPageTabTitle('添加付款单信息');
      if(this.isUpdate == 2)  setPageTabTitle('修改付款单信息');
      if(this.isUpdate == 3)  setPageTabTitle('查看付款单信息');
    },
    methods: {

      /* 初始化数据 */
      async initData(){

        GetAllBackAccount().then((res)=>{
          this.bankAccountDatas = [];
          this.bankAccountDatas = res;
        });

        QueryAllChildDictViewByCode(this.Constant.C_HB).then((res)=>{
          this.currencyDatas = [];
          this.currencyDatas = res;

          this.currencyFilterDatas = [];
          this.currencyFilterDatas = res;

          res.map((d)=>{
            if(d.code =='C-HB01'){
              this.RMBId = d.id;
            }
          });
        });

        GetAllBSupplier().then((res)=>{
          this.supplierDatas = [];
          this.supplierDatas = res;
        });

      },

      /* 保存编辑 */
      save() {
        //校验必填信息
        this.$refs['form'].validate((valid) => {
          if (!valid) {return false;}
          this.loading = true;
          const saveOrUpdate = this.isUpdate ==2 ? UpdatePayment : AddPayment;
          saveOrUpdate(this.form)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.updateVisible();
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        });
      },

      /* 过账 */
      settle() {
        //校验必填信息
        this.$refs['form'].validate((valid) => {
          if (!valid) {return false;}

          this.loadingAudit = true;
          AuitPayment(this.form)
            .then((msg) => {
              this.loadingAudit = false;
              this.$message.success(msg);
              this.updateVisible();
            })
            .catch((e) => {
              this.loadingAudit = false;
              this.$message.error(e.message);
            });
        });
      },

      unAudit(){
        this.loadingUnAudit = true;
        AntiPayment(this.form.id)
        .then((msg) => {
          this.loadingUnAudit = false;
          this.$message.success(msg);
          this.updateVisible();
        })
        .catch((e) => {
          this.loadingUnAudit = false;
          this.$message.error(e.message);
        });
      },

      setData(id){
        QueryPaymentById(id)
          .then((res) => {
            this.form = res;
            this.changeCurrency(res.currencyId);
        });
      },

      OpenProductList(){
        if(this.form.supplierId && this.form.currencyId){
          this.showrecreceiptList =true;
          this.current ={supplierId: this.form.supplierId,currencyId:this.form.currencyId,rmb:this.RMBId};
        }else{
          this.$message.info("请选择供应商与币种");
          return;
        }
      },

      changeCurrency(val){
        QueryModelByScurrencyId(val).then((d)=>{
          this.form.rate =d?d.rate:1;
          this.computeDirection = d?d.computeDirection:1;
        })
      },


      changeSupplier(val){

        if(this.supplierDatas){
          let supplier = this.supplierDatas.find((d)=>{return d.id == val});

          if(supplier){
            this.form={rate:0,currencyId:'',supplierId:val,payAmount:0,payAmountCn:0,auitAmount:0,auitAmountCn:0,items:[]};

            this.form.supplierTypeId = supplier.typeId;
            this.form.currencyId = supplier.currencyId;
            
            let filterCurrencys = this.currencyDatas.filter((c)=>{
              return (c.id == this.RMBId || c.id == this.form.currencyId)
            });

            this.currencyFilterDatas=[];
            this.currencyFilterDatas=filterCurrencys;
            this.changeCurrency(supplier.currencyId);
          }
        }
      
      },

      changeBackAccount(val){

        if(this.bankAccountDatas){
          let bankAccount = this.bankAccountDatas.find((d)=>{return d.id == val});

          if(bankAccount){
            this.form.currencyId = bankAccount.currencyId;
            
            let filterCurrencys = this.currencyDatas.filter((c)=>{
              return (c.id == this.RMBId || c.id == this.form.currencyId)
            });

            this.currencyFilterDatas=[];
            this.currencyFilterDatas=filterCurrencys;
            this.changeCurrency(this.form.currencyId);
          }
        }
      },
      //设置金额
      setAmount(row,index){

        if(row.auitAmount ){
          if(parseFloat(row.auitAmount)>parseFloat(row.recAmount)){
            this.$message.info('核销金额不能大于应付金额');
            row.auitAmount = row.recAmount;
            return;
          }
        }

        if(row.auitAmount && row.rate){
          let r = parseFloat(row.rate);
          let a = parseFloat(row.auitAmount);
          this.$refs.items.data[index].auitAmountCn =this.computeDirection ==1? (a * r).toFixed(4):(a / r).toFixed(4);
        }

        if(row.payAmount && row.rate){
          let rq = parseFloat(row.rate);
          let ra = parseFloat(row.payAmount);
          this.$refs.items.data[index].payAmountCn =this.computeDirection ==1?(ra * rq).toFixed(4):(ra / rq).toFixed(4);
        }

        this.setAmountTotal();

      },

      reloadauitList(items){
        this.form.items = [];
        items.map((i)=>{
          this.form.items.push({
            rate:i.rate,
            paymentId:this.form.id,
            orderNo:i.orderNo,
            orderId:i.orderId,
            orderType:i.auitOrderType,
            supplierId:i.supplierId,
            payAmount:i.surplusAmount,
            auitAmount:i.surplusAmount,
            currencyId:i.currencyId,
            payAmountCn:i.surplusAmountCn,
            auitAmountCn:i.surplusAmountCn,
            supplierTypeId:i.supplierTypeId,
            auitOrderId:i.id,
          })
        });

        this.setAmountTotal();
      },


      //设置提成金额汇总
      setAmountTotal(){
        this.form.payAmount = 0;
        this.form.payAmountCn = 0;
        this.form.auitAmount = 0;
        this.form.auitAmountCn = 0;

        if(this.form.items!=null && this.form.items!=undefined && this.form.items.length>0){

          this.form.payAmount = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.payAmount)  },0);
          this.form.auitAmount = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.auitAmount)  },0);
          this.form.payAmountCn = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.payAmountCn)  },0);
          this.form.auitAmountCn = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.auitAmountCn)  },0);

          this.form.payAmount = (this.form.payAmount).toFixed(4);
          this.form.auitAmount = (this.form.auitAmount).toFixed(4);
          this.form.payAmountCn = (this.form.payAmountCn).toFixed(4);
          this.form.auitAmountCn = (this.form.auitAmountCn).toFixed(4);

        }
      },

      /* 删除 */
      remove(_row, index) {
        this.form.items.splice(index, 1);
        this.setAmountTotal();
      },

      /* 更新visible */
      updateVisible() {
        removePageTab({ key: this.$route.path });
        reloadPageTab({ fullPath: '/financialmanager/paymentmanager' });
      },

      handleClose() {
        removePageTab({ key: this.$route.path });
        this.$router.push('/financialmanager/paymentmanager');
      },

      clickbillNo(row){
        removePageTab({ key: '/businesshandling/purordermanager' });
        this.$nextTick(() => {
          this.$router.push({path: '/businesshandling/purordermanager', query: { "billNo": row.orderNo } });
        });
      },

      /* 合计 */
      getSummaries(param){
        const sums = [];
        sums[0] = '合计' ;
        const { columns, data } = param;
        columns.forEach((column, index) => {
          if(index ==2){
            sums[index] =  Number(this.form.payAmount).toFixed(4);
          }else if(index ==3){
            sums[index] = Number(this.form.auitAmount).toFixed(4);
          }else if(index ==6){
            sums[index] = Number(this.form.payAmountCn).toFixed(4);
          }else if(index ==7){
            sums[index] = Number(this.form.auitAmountCn).toFixed(4);
          }
        });

        this.$nextTick(() => {
          this.$refs.items.doLayout();
        });
        return sums;
      },

      /* 样式 */
      cellStyle(param){
        const { row, column, rowIndex, columnIndex } = param;
        if(columnIndex==2||columnIndex==3||columnIndex==4||columnIndex==6||columnIndex==7){
          return{
            color:''
          }
        }
      },
  },
   
    /* 监听visible属性变化 */
    watch: {
      visible(visible) {
        if (visible) {
          if (this.data && this.data.id) {
            //赋值this.form
            this.setData(this.data.id);
            this.isUpdate = this.data.id !=null && this.data.id !=undefined;
          } else {
            this.form={rate:0,currencyId:'',payAmount:0,payAmountCn:0,auitAmount:0,auitAmountCn:0};
            this.isUpdate = false;
          }
        } else {
            this.$refs['form'].clearValidate();
            this.form={rate:0,currencyId:'',payAmount:0,payAmountCn:0,auitAmount:0,auitAmountCn:0};
        }
      }
    }
  };
</script>
<style lang="scss" scoped>
/*总计字体颜色
::v-deep .el-table__footer-wrapper tbody td {
  color: var(--color-primary);
  cursor: pointer;
}*/
</style>